package com.yuma.lock;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;

class MyCache{

     public Map<String, String> cache= new HashMap<>();
    // 1.解决同步问题
    // public Map<String, String> cache= new ConcurrentHashMap<>();

    // 2.同步块/同步方法

    // 3.读写锁: 读多写少的时候使用
    private volatile ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

    //写
    public void put(String key, String value){
        // 写锁： 独占锁
        lock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + " 开始写入！" + value);
            Thread.sleep(300);
            cache.put(key, value);
            System.out.println(Thread.currentThread().getName() + " 写入成功！" + value);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        lock.writeLock().unlock();
    }

    //读
    public void get(String key){
        // 读锁： 是共享锁，多个线程都可以持有
        lock.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + " 开始读出！");
            Thread.sleep(300);
            String value = cache.get(key);
            System.out.println(Thread.currentThread().getName() + " 读出成功！" + value);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        lock.readLock().unlock();
    }
}

public class ReentrantReadWriteLockDemo {

    public static void main(String[] args) throws InterruptedException {

        MyCache cache = new MyCache();

        for (int i = 1; i <= 5; i++) {
            String num = String.valueOf(i);   // String num = i+"";
            // 开启5个写线程
            new Thread(()->{
                cache.put(num, num);
            }, num).start();
        }

        for (int i = 1; i <= 5; i++) {
            String num = String.valueOf(i);
            // 开启5个读线程
            new Thread(()->{
                cache.get(num);
            }, num).start();
        }

    }
}
